package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import io.swagger.v3.core.util.Json;
import jakarta.validation.ConstraintViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * ControllerAdvice注解:
 *   1.标识该类为全局异常处理器的类;
 *   2.当控制器抛出异常时,框架会检查是否定义了全局异常处理器;
 *
 * RestControllerAdvice注解:
 *   1.组合注解,等价于 ControllerAdvice + ResponseBody;
 *   2.添加该注解后,所有的异常处理方法上就无需再添加 ResponseBody 注解了;
 */
@Slf4j
@RestControllerAdvice
public class GlobaExceptionHandler {
    /**
     * ExceptionHandler注解:标识当前方法为异常处理方法,需要指定异常的类型;
     */

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public JsonResult doHandle(IllegalArgumentException ex){
        //获取异常提示消息：throw new IllegalAccessException("车辆ID不能小于0");
        String date = ex.getMessage();
        //打印日志
        log.error("IllegalArgumentException"+date);
        return new JsonResult(StatusCode.OPERATION_FAILED,date);
    }

    @ExceptionHandler(RuntimeException.class)
    public JsonResult donHandleRuntimeExcepion(RuntimeException  ex){
        String date = ex.getMessage();
        log.error("RuntimeException"+date);
        return new JsonResult(StatusCode.OPERATION_FAILED,date);
    }

    /**
     * 1.异常处理方法，处理Validation验证框架封装参数时出现的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String date = ex.getFieldError().getDefaultMessage();
        log.debug("MethodArgumentNotValidException:" + date);
        return new JsonResult(StatusCode.VALIDATEN_ERROR, date);
    }

    /**
     * 2.异常处理方法:Validation验证非封装参数时出现的异常;
     *   ConstraintViolationException
     */

    @ExceptionHandler(ConstraintViolationException.class)
    public JsonResult dohandleConstraintViolationException(ConstraintViolationException ex){
        String date = ex.getMessage().split(":")[1].trim();
        log.debug("ConstraintViolationException:" + date);
        return new JsonResult(StatusCode.VALIDATEN_ERROR, date);
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public JsonResult doHandleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex){
        String date = "上传文件大小超出限制";
        log.debug("MaxUploadSizeExceededException:" + date);
        return new JsonResult(StatusCode.FILE_UPLOAD_ERROR, date);
    }






/*
    /**
     *可以处理所有异常方法
     *
     *
    @ExceptionHandler(Throwable.class)
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("Throwable:" + data);
        return new JsonResult(StatusCode.THROWABLE_ERROR, data);
    }

 */
}
